import React from 'react';
import menuRoute from 'routes/menuRoute';
import contractService from 'containers/approve/contract/contract.service';
import {
  Form,
  Row,
  Col,
  Spin,
  message,
  Popover,
  Popconfirm,
  Breadcrumb,
  Tag
} from 'antd';
import config from 'config';
import moment from 'moment';
import DocumentBasicInfo from 'containers/contract/document-basic-info';
import 'styles/contract/my-contract/contract-detail.scss';
import ApproveHistory from 'components/template/approve-history'
import { messages } from 'share/common';
import CustomTable from 'containers/setting/contract-type-define/custom-table';


class ContractDetailCommon extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detailLoading: true,
      planLoading: false,
      historyLoading: false,
      topTapValue: 'contractInfo',
      headerData: {},
      payPlanVisible: false,
      payInfo: {},
      approveHistory: [],
      prepaymentData: [],    //关联的预付款单
      AccountData: [],       //关联的报账单
      contractEdit: false, //合同是否可编辑
      contractStatus: {
        6002: { label: messages('my.contract.state.cancel'/*已取消*/), state: 'default' },
        6003: { label: messages('my.contract.state.finish'/*已完成*/), state: 'success' },
        1001: { label: messages('my.contract.state.generate'/*编辑中*/), state: 'processing' },
        6001: { label: messages('my.contract.state.hold'/*暂挂*/), state: 'warning' },
        1002: { label: messages('my.contract.state.submitted'/*审批中*/), state: 'processing' },
        1005: { label: messages('my.contract.state.rejected'/*已驳回*/), state: 'error' },
        1004: { label: messages('my.contract.state.confirm'/*已通过*/), state: 'success' },
        1003: { label: messages('my.contract.state.withdrawal'/*已撤回*/), state: 'warning' },
      },
      columns: [
        { title: messages('my.contract.currency'/*币种*/), dataIndex: 'currency', align: 'center', },
        {
          title: messages('request.amount'/*金额*/), dataIndex: 'amount', align: 'center',
          render: desc => this.filterMoney(desc)
        },
        {
          title: messages('request.base.amount'/*本币金额*/), dataIndex: 'funcAmount', align: 'center',
          render: (desc, record) => this.filterMoney(record.amount)
        },
        {
          title: messages('my.receivable'/*收款方*/), dataIndex: 'partnerName', align: 'center',
          render: (value, record) => {
            return (
              <div>
                <Tag color="#000">{record.partnerCategory == 'EMPLOYEE' ? messages('acp.employee') : messages('acp.vendor')}</Tag>
                <div style={{ whiteSpace: 'normal' }}>{record.partnerCategory === 'EMPLOYEE' ? record.partnerName + '-' + record.partnerId : record.partnerName}</div>
              </div>
            );
          }
        },
        {
          title: messages('my.contract.plan.pay.date'/*计划付款日期*/),
          dataIndex: 'dueDate',
          align: 'center',
          render: value => <Popover content={value ? moment(value)
            .format('YYYY-MM-DD') : '-'}>{value ? moment(value)
            .format('YYYY-MM-DD') : '-'}</Popover>
        },
        {
          title: messages('common.remark'/*备注*/), dataIndex: 'remark', align: 'center',
          render: value => value ? <Popover placement="topLeft" content={value}
                                            overlayStyle={{ maxWidth: 300 }}>{value}</Popover> : '-'
        }
      ],
      data: [],
      showSlideFrame: false,
      slideFrameTitle: '',
      btnVisible: true,
      documentParams: {},
      record: {}, //资金计划行信息
      historyData: [], //历史信息
      EditContract: menuRoute.getRouteItem('edit-contract', 'key'), //编辑合同
      data1: [],
      pagination1: {
        total: 0
      },
      page1: 0,
      pageSize1: 10
    };
  }

  componentDidMount() {
    this.getInfo();
  }

  //获取合同信息
  getInfo = () => {
    const { columns } = this.state;
    this.setState({ detailLoading: true });
    contractService.getContractHeaderInfo(this.props.id)
      .then(response => {
        if (response.data.status === 1001 ||
          response.data.status === 1003 ||
          response.data.status === 1005) { //编辑中、已驳回、已撤回
          columns.splice(columns.length, 0,
            {
              title: messages('common.operation'/*操作*/),
              dataIndex: 'id',
              width: '10%',
              render: (text, record) => (
                <span>
                <a onClick={(e) => this.editItem(e, record)}>{messages('common.edit'/*编辑*/)}</a>
                <span className="ant-divider"/>
                <Popconfirm title={messages('common.confirm.delete'/*确定要删除吗？*/)}
                            onConfirm={(e) => this.deleteItem(e, record)}>
                  <a>{messages('common.delete'/*删除*/)}</a>
                </Popconfirm>
              </span>)
            }
          );
        }
        let documentParams = {
          formName: response.data.contractTypeName,
          totalAmount: response.data.amount ? response.data.amount : 0,
          statusCode: response.data.status,
          remark: response.data.remark,
          businessCode: '12',
          currencyCode: response.data.currency,
          infoList: [
            { label: messages('my.contract.number'), value: response.data.contractNumber },
            {
              label: messages('common.applicant'),
              value: response.data.created && response.data.created.fullName + '-' + response.data.created.employeeId
            },
            { label: messages('my.contract.category'), value: response.data.contractCategoryName },
          ],
          attachments: response.data.attachments
        };
        this.setState({
          columns,
          documentParams,
          btnVisible: !response.data.contractName,
          headerData: response.data,
          detailLoading: false
        }, () => {
          this.getHistory(response.data.documentOid);
          this.props.getContractStatus(this.state.headerData.status);
          // this.getPrepaymentHeadByContract();
          // this.getAccountHeadByContract();
        });
      })
      .catch(e => {
        message.error(messages('common.error'/*哦呼，服务器出了点问题，请联系管理员或稍后再试:(*/));
      });
  };

  getHistory = (oid) => {
    contractService.getContractHistory(oid)
      .then(response => {
        this.setState({
          approveHistory: response.data
        });
      });
  };

  //获取合同关联的预付款单
  getPrepaymentHeadByContract() {
    let { headerData } = this.state;
    contractService.getPrepaymentHeadByContractNumber(headerData.id)
      .then(res => {
        this.setState({
          prepaymentData: res.data
        }, () => { });
      })
      .catch(e => {
        if (e.response) {
          message.error(response.data.message);
        }
      });
  }

  //获取合同关联的报账单
  getAccountHeadByContract() {
    let { headerData } = this.state;
    contractService.getAccountHeadByContract(headerData.id)
      .then(res => {
        this.setState({
          AccountData: res.data
        });
      });
  }

  render() {
    const { approveHistory, detailLoading, planLoading, documentParams, columns, headerData, } = this.state;


    return (
      <div className="contract-content" style={{}}>
        <div className="document-basic-info" style={{}}>
          <DocumentBasicInfo params={documentParams} noHeader={true}/>
        </div>
        <Spin spinning={detailLoading}>
          <div className="contract-info">
            <div className="contract-info-header" style={{ borderBottom: '1px solid rgb(236, 236, 236)' }}>
              <h3 style={{
                display: 'inline',
                marginLeft: '20px',
                fontSize: '18px'
              }}>{messages('my.create.contract.info')}</h3>
            </div>

            <div style={{ marginLeft: 15 }}>
              <Row gutter={24} className="info-items">
                <Col span={2} className="label-tips">{messages('common.baseInfo')}:</Col>

                <Col span={2} offset={1} className="item-label">{messages('my.contract.contractCompany')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.companyName}>{headerData.companyName}</span></Col>

                <Col span={2} className="item-label">{messages('acp.contract.name')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.contractName}>{headerData.contractName}</span></Col>

                <Col span={2} className="item-label">{messages('my.contract.signDate')}:</Col>
                <Col span={5} className="item-value">
                  <span
                    title={headerData.contractName ? headerData.signDate ? moment(new Date(headerData.signDate))
                      .format('YYYY-MM-DD') : '-' : ''}>
                    {headerData.contractName ? headerData.signDate ? moment(new Date(headerData.signDate))
                      .format('YYYY-MM-DD') : '-' : ''}
                  </span>
              </Col>
              </Row>

              <Row gutter={25} className="info-items">
                <Col span={2} className="label-tips">{messages('my.contract.party.info')}:</Col>
                <Col span={2} offset={1} className="item-label">{messages('my.contract.partner.category')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.partnerCategoryName}>{headerData.partnerCategoryName}</span></Col>
                <Col span={2} className="item-label">{messages('my.contract.partner')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.partnerName}>{headerData.partnerName}</span></Col>
              </Row>

              <Row gutter={24} className="info-items">
                <Col span={2} className='label-tips'>{messages('supplier.management.otherInfo')}:</Col>
                <Col span={2} offset={1} className="item-label">{messages('my.contract.responsible.department')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.unitName}>{headerData.contractName ? headerData.unitName ? headerData.unitName : '-' : ''}</span></Col>
                <Col span={2} className="item-label">{messages('my.contract.responsible.person')}:</Col>
                <Col span={5} className="item-value"><span title={headerData.employeeId}>{headerData.contractName ? headerData.employee ? headerData.employee.fullName : '-' : ''}</span></Col>
                <Col span={2} className="item-label">{messages('budget.controlRule.effectiveDate')}:</Col>
                <Col span={5} className="item-value">
                  <span
                    title={headerData.contractName ? (headerData.startDate ? moment(new Date(headerData.startDate))
                      .format('YYYY-MM-DD') : '-') + ' ~ ' + (headerData.endDate ? moment(new Date(headerData.endDate))
                      .format('YYYY-MM-DD') : '-') : ''}>
                      {headerData.contractName ? (headerData.startDate ? moment(new Date(headerData.startDate))
                        .format('YYYY-MM-DD') : '-') + ' ~ ' + (headerData.endDate ? moment(new Date(headerData.endDate))
                        .format('YYYY-MM-DD') : '-') : ''}
                  </span>
                </Col>
              </Row>
            </div>
          </div>
        </Spin>
        <Spin spinning={planLoading}>
          <div className="pay-info" style={{ marginLeft: 0 }}>
            <h3 className="info-header-title" style={{
              borderBottom: '1px solid #ececec',
              fontSize: 18,
              padding: '20px 20px 10px',
              margin: '-20px -20px 20px'
            }}>
              {messages('acp.payment.info')}
            </h3>
            <Row gutter={24} className="pay-info-header"
                 style={headerData.status === 6001 || headerData.status === 6003 || headerData.status === 6002 || headerData.status === 1002 ? { marginTop: -20 } : {}}>
              <Col span={12}/>
              <Col span={12} className="header-tips" style={{ textAlign: 'right' }}>
                <Breadcrumb style={{ marginBottom: '10px' }}>
                  <Breadcrumb.Item>{messages('common.amount')}:&nbsp;
                    <span style={{ color: 'Green' }}> {headerData.currency}&nbsp;{this.filterMoney(headerData.amount)}</span>
                  </Breadcrumb.Item>
                  <Breadcrumb.Item>{messages('acp.function.amount')}:
                    <span style={{ color: 'Green' }}> {headerData.currency}&nbsp;{this.filterMoney(headerData.amount)}</span>
                  </Breadcrumb.Item>
                </Breadcrumb>
              </Col>
            </Row>
            <CustomTable
              ref={ref => this.table = ref}
              url={`${config.contractUrl}/api/contract/line/herder/${this.props.id}`}
              showNumber={true}
              pagination={{ pageSize: 5 }}
              columns={columns}/>
          </div>
        </Spin>
        <div className="history">
          {
            approveHistory[0] &&
            <section className="history-body">
              <h3 className="info-header-title">{messages('approve.key128')/*审批信息*/}</h3>
              <ApproveHistory businessCode={headerData.contractNumber}
                              isShowReply={true}
                              approvalHistory={approveHistory}/>
            </section>
          }
        </div>
      </div>
    );
  }
}

ContractDetailCommon.propTypes = {
  id: React.PropTypes.any.isRequired, //显示数据
  isApprovePage: React.PropTypes.bool, //是否在审批页面
  getContractStatus: React.PropTypes.func, //确认合同信息状态
};

ContractDetailCommon.defaultProps = {
  isApprovePage: false,
  getContractStatus: () => {
  }
};

ContractDetailCommon.contextTypes = {
  router: React.PropTypes.object
};

const wrappedContractDetailCommon = Form.create()((ContractDetailCommon));

export default wrappedContractDetailCommon;
